<?php

namespace App\Console\Crons;

use App\Models\Log\LogMtgHotSearchData;
use App\Models\MtgHotSearchConfig;
use App\Services\MiniprogramToGame\HotSearchService;

class MtgHotSearchCron extends CronBase
{
    private function trimString($msg, $length = 2000) {
        if (mb_strlen($msg, 'UTF-8') > $length) {
            $msg = mb_substr($msg, 0, $length, 'UTF-8');
            $msg = mb_substr($msg, 0, mb_strrpos($msg, ' ', 0, 'UTF-8'), 'UTF-8');
            $msg .= '...';
        }

        return $msg;
    }

    public function run($stime)
    {
        $stat_date = strtotime('today');
        $media_list = array_keys(MtgHotSearchConfig::MEDIA_LIST);
        foreach ($media_list as $media) {
            $class_name = ucfirst($media);
            $file = "App\\Services\\MiniprogramToGame\\HotSearch\\{$class_name}";
            $class = new $file();
            $data = $class->reptile();
            if (empty($data)) {
                yqlog($media, $class_name);
                continue;
            }

            $list = [];
            foreach ($data as $val) {
                $list[] = [
                    'stat_date'  => $stat_date,
                    'media_name' => $media,
                    'title'      => $val->title,
                    'desc'       => $this->trimString($val->desc),
                    'url'        => $val->url,
                    'img'        => $val->img,
                    'hot_index'  => $val->hotIndex,
                    'hot_value'  => $val->hotValue,
                    'is_top'     => $val->isTop,
                ];
            }

            LogMtgHotSearchData::whereRaw("stat_date={$stat_date} AND media_name='{$media}'")->delete();
            foreach ($list as $insert_data) {
                LogMtgHotSearchData::insert($insert_data);
            }
        }
    }
}
